const net = require("net");
const eventEmit = require('./utils/MyEventEmit')
const chalk = require("chalk");
const {socketServer,socketServerPort, isOpenMockSocket} = require("./config/config");

module.exports = class MySocket {
    #socket = null;
    isOpened = false
    async init(){
        if (this.#socket === null){
          await this.initInstance();
        }
    }
    initInstance(){
        this.#socket = new net.Socket();
        this.#socket.connect(socketServerPort,socketServer);
        this.#socket.setTimeout(5000);
        return new Promise((resolve, reject) => {
            this.#socket.on('connect',()=>{
                console.log('connect');
                this.receiveData();
                resolve();
            })
            this.#socket.on('finish',()=>console.log('finish'));
            this.#socket.on('error',(e)=>{
                console.log(chalk.red('error断开'));
                this.handleError(e);
                reject();
            });
            this.#socket.on('timeout',e => {
                console.log(chalk.red('timeout断开'));
                this.handleError(e);
                reject();
            })
        })
    }
  async openBreath(){
        if (this.isOpened){
            return {
                isOpened : true,
                needInit: false
            }
        }
        try {
            await this.init();
            let uint8Array = new Uint8Array([0x00,0x01,0x00,0x00]);
            this.#socket.write(uint8Array);
            this.isOpened = true
            return {
                isOpened : true,
                needInit: true
            }
        }catch (e) {
            this.isOpened = false
            return {
                isOpened : false,
                needInit: false
            }
        }
    }
  async setBreathAmplitude(val){
      let uint8Array = new Uint8Array([0x00,0x02,val,0x00]);
      this.#socket.write(uint8Array);
  }

  closeBreath(){
        let uint8Array = new Uint8Array([0x00,0x00,0x00,0x00]);
        this.#socket.write(uint8Array);
        this.destroyBreath()
    }
    destroyBreath(){
        if (this.#socket!==null){
            this.#socket.destroy();
            this.#socket = null;
            this.isOpened = false;

        }
    }
    _handleData(data){
        this.sendData(data);
    }
    sendData(data){
        eventEmit.emit('breathData',Buffer.from(data));
    }
    receiveData(){
        this.#socket.on('data',data => this._handleData(data))
    }
    handleError(e){
        this.destroyBreath();
    }
}
